#include "timer.h"
/*设置TIMER3 CH1(HALL-A PA6) CH2(HALL-B PA7) CH3(HALL-C PB0)为输入捕获模式，异或逻辑输入*/
void TIMER3_Init(void)
{
    /*打开RCC TIMER3时钟*/
    RCC -> APBENR1 |= 0x00000002;
    TIM3->CR1 = 0x80;/*使能ARR预装载*/
    TIM3->PSC = 128;//2us CNT ++ 一次   
    TIM3->ARR = 65535;
    TIM3->CNT = 0;
    TIM3->DIER = 0x00000001;/*使得Update中断*/
    /*使能计数器*/
    //TIM3->CR1 = 0x01;	
}

void TIMER14_Init(void)
{
    /*打开RCC TIMER3时钟*/
    RCC -> APBENR2 |= 0x00008000;
    TIM14->CR1 = 0x80;/*使能ARR预装载*/
    TIM14->PSC = 128;//2us CNT ++ 一次   
    TIM14->ARR = 65535;
    TIM14->CNT = 0;
    TIM14->DIER = 0x00000001;/*使得Update中断*/
    /*使能计数器*/
    TIM14->CR1 = 0x01;	    
}

/*设置TIMER16 CH1(PB8) TIMER17 CH1(PB9)为输出比较模式，输出50khz的PWM波，配合外围的RC电路实现DAC转换，供外部读取调试*/
void TIMER16_17_Init(void)
{
    /*打开TIMER16、TIMER17时钟*/
    U32SetBit(RCC->APBENR2,17);
    U32SetBit(RCC->APBENR2,18);
    /*配置CH1 IO口模式为复用*/
    #if (TIM16_USED_BY == DEBUG)
    U32SetBitField(GPIOB->MODER,16,17,2);//A8
    #endif
    U32SetBitField(GPIOB->MODER,18,19,2);//A9
    /*配置IO口速度为高速*/
    #if (TIM16_USED_BY == DEBUG)
    U32SetBitField(GPIOB->OSPEEDR,16,17,2);//A8
    #endif    
    U32SetBitField(GPIOB->OSPEEDR,18,19,2);//A9
    /*配置复用号*/
    #if (TIM16_USED_BY == DEBUG)    
    U32SetBitField(GPIOB->AFR[1],0,3,2);//A8
    #endif    
    U32SetBitField(GPIOB->AFR[1],4,7,2);//A9    

    #if (TIM16_USED_BY == DEBUG)
    /*TIMER 16*/
    TIM16->CR1 |= (1<<7);/*使能ARR预装载*/
    U32SetBitField(TIM16->CCMR1,4,6,6);/*PWM Mode 1*/
    TIM16->CCMR1 |= (1<<3);/*使能CCR预装载*/
    U32SetBitField(TIM16->CCMR1,0,1,0);/*CC1 channel is configured as output*/

    TIM16->CCER |= 0x00000001;/*使能OC1*/

    /*配置PSC和ARR，产生50HZ的波形*/
    TIM16->PSC = 0;
    TIM16->ARR = 1280 - 1;/*64000000/1280 = 50000*/
    TIM16->CCR1 = 1280;/*初始占空比50，也即3.3/2 = 1.65v*/

    TIM16->AF1 &=~ (1<<0);/*失能刹车输入*/
    TIM16->BDTR |= (1<<15);/*MOE = 1 使能PWM输出*/
    /*使能计数器*/
    TIM16->CR1 |= 0x00000001;
    #endif
    /*TIMER 17*/
    TIM17->CR1 |= (1<<7);/*使能ARR预装载*/
    U32SetBitField(TIM17->CCMR1,4,6,6);/*PWM Mode 1*/
    TIM17->CCMR1 |= (1<<3);/*使能CCR预装载*/
    U32SetBitField(TIM17->CCMR1,0,1,0);/*CC1 channel is configured as output*/

    TIM17->CCER |= 0x00000001;/*使能OC1*/

    /*配置PSC和ARR，产生50HZ的波形*/
    TIM17->PSC = 0;
    TIM17->ARR = 1280 - 1;/*64000000/1280 = 50000*/
    TIM17->CCR1 = 640;/*初始占空比50，也即3.3/2 = 1.65v*/    

    TIM17->AF1 &=~ (1<<0);/*失能刹车输入*/    
    TIM17->BDTR |= (1<<15);/*MOE = 1 使能PWM输出*/
    /*使能计数器*/
    TIM17->CR1 |= 0x00000001;
}

// void TIM3_IRQHandler(void)
// {
//     xBldcRunMode.u16HallVal = BldcGetHallValue();
//     xBldcRunMode.ePhase = BldcHallValToPhase(xBldcRunMode.u16HallVal,xMotorMode.dir);
//     if( PHASE_ERROR != xBldcRunMode.ePhase ){
//         BldcPwmControl(xBldcRunMode.ePhase);                
//     }

//     if( eMotorGetState()== MotorSelfStart )
//     {
//         xMotorMode.selfStartSwitchCnt++;
//         setMotorStartCnt(0);
//     }

//     TIM3 -> SR = 0;
// }
